package com.interfaces.module.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.interfaces.aspect.auth.LoginAuth;
import com.interfaces.module.goods.domain.FtsGoods;
import com.interfaces.module.goods.service.FtsGoodsService;
import com.interfaces.module.order.domain.FtsOrder;
import com.interfaces.module.order.domain.FtsOrderList;
import com.interfaces.module.order.service.FtsOrderListService;
import com.interfaces.module.order.service.FtsOrderService;
import com.interfaces.module.order.vo.PrePayVo;
import com.interfaces.module.user.domain.FtsUser;
import com.interfaces.module.user.domain.FtsUserAddress;
import com.interfaces.module.user.domain.FtsUserCollect;
import com.interfaces.module.user.service.FtsUserAddressService;
import com.interfaces.util.Result;
import com.interfaces.util.TokenUtil;
import com.interfaces.wx.pay.WxJsapiService;
import com.ruoyi.framework.web.domain.server.Sys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class FtsOrderController {
    @Autowired
    private FtsGoodsService ftsGoodsService;
    @Autowired
    private FtsOrderService ftsOrderService;
    @Autowired
    private FtsOrderListService ftsOrderListService;
    @Autowired
    private FtsUserAddressService ftsUserAddressService;

    /**
     * 预支付订单
     * @param prePayVos
     * @return
     */
    @Transactional
    @LoginAuth(flag = true)
    @RequestMapping("/prePay")
    public Result prePay(@RequestBody List<PrePayVo> prePayVos){
        FtsUser ftsUser=TokenUtil.getTokenUser();
        FtsOrder ftsOrder=new FtsOrder();
        QueryWrapper<FtsUserAddress> ftsUserAddressQueryWrapper=new QueryWrapper<FtsUserAddress>();
        ftsUserAddressQueryWrapper.eq("user_id",ftsUser.getId());
        ftsUserAddressQueryWrapper.eq("default_flag",1);
        /***************地址处理*******************/
        FtsUserAddress ftsUserAddress=ftsUserAddressService.getOne(ftsUserAddressQueryWrapper);
//        if(null==ftsUserAddress){
//            return Result.ERROR("请先录入收货地址!");
//        }
        if(null!=ftsUserAddress){
            StringBuffer addressStr=new StringBuffer(ftsUserAddress.getProvince());
            addressStr.append(ftsUserAddress.getCity());
            addressStr.append(ftsUserAddress.getCounty());
            addressStr.append(ftsUserAddress.getDetail());
            ftsOrder.setShippingAddress(addressStr.toString());
            ftsOrder.setShippingAddressId(ftsUserAddress.getId());
        }

        /*******************************************/
//        for (PrePayVo prePay:prePayVos) {
//
//        }
        String  outTradeNo=WxJsapiService.outTradeNoGen();
        ftsOrder.setOrderCode(outTradeNo);

        ftsOrder.setPayUserId(ftsUser.getId());
        ftsOrder.setPayState(1);
        ftsOrder.setState(1);
        ftsOrder.setCreateUserId(ftsUser.getId());

        ftsOrder.setCreateBy(ftsUser.getNickName());
        ftsOrder.setCreateTime(new Date());
        ftsOrder.setUpdateTime(new Date());
        ftsOrderService.save(ftsOrder);

        List<FtsOrderList> ftsOrderLists=new ArrayList<>();
        final BigDecimal[] totalPrice = {new BigDecimal(0.00)};
        prePayVos.forEach(item->{

            int goodsNumber=item.getGoodsNumber();
            //这里或许再加入规格查询，如果后续有
            FtsGoods ftsGoods=ftsGoodsService.getById(item.getGoodsId());
            BigDecimal price =ftsGoods.getPrice();
            BigDecimal prices=price.multiply(new BigDecimal(goodsNumber)).setScale(2);
            totalPrice[0] = totalPrice[0].add(prices);
            /******************子订单设置*************************/
            FtsOrderList ftsOrderList=new FtsOrderList();
            ftsOrderList.setOrderId(ftsOrder.getId());
            ftsOrderList.setGoodsId(item.getGoodsId());
            ftsOrderList.setGoodsNumber(item.getGoodsNumber());
            ftsOrderList.setGoodsPrice(ftsGoods.getPrice());
            ftsOrderList.setGoodsCover(ftsGoods.getCover());
            ftsOrderList.setGoodsSpec(item.getSpec());
            ftsOrderList.setGoodsTitle(ftsGoods.getTitle());
            ftsOrderList.setOrderCode(outTradeNo);
            ftsOrderList.setOrderListCode(outTradeNo+"_"+item.getGoodsId());
            /*******************************************/
            ftsOrderLists.add(ftsOrderList);
        });
        ftsOrderListService.saveBatch(ftsOrderLists);
        ftsOrder.setPrice(totalPrice[0]);

        boolean orderFlag=ftsOrderService.updateById(ftsOrder);
        ftsOrder.setFtsOrderListList(ftsOrderLists);
        return Result.SUCCESS(outTradeNo);
    }

    /**
     * 支付完成回调
     * @param outTradeNo
     * @param payState
     * @return
     */
    @Transactional
    @LoginAuth(flag = true)
    @RequestMapping("/payResult")
    public Result payResult(String outTradeNo,Integer payState){
        FtsOrder ftsOrder=new FtsOrder();
        ftsOrder.setOrderCode(outTradeNo);
        ftsOrder.setPayState(payState);
        ftsOrder.setState(payState);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("order_code",outTradeNo);
        ftsOrderService.update(ftsOrder,queryWrapper);
        List<FtsOrderList> ftsOrderListData=ftsOrderListService.list(queryWrapper);
        ftsOrderListData.stream().forEach(item->{
            FtsGoods ftsGoods=ftsGoodsService.getById(item.getGoodsId());
            int sales=ftsGoods.getSales();
            int stock=ftsGoods.getStock();
            sales+=item.getGoodsNumber();
            stock-=item.getGoodsNumber();
            ftsGoods.setSales(sales);
            ftsGoods.setStock(stock);
            ftsGoodsService.updateById(ftsGoods);
        });
        return Result.SUCCESS(outTradeNo);
    }
    /**
     * 查询预支付订单
     * @param orderCode
     * @return
     */
    @RequestMapping("/findPrePay")
    public Result findPrePay(String orderCode){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("order_code",orderCode);
        FtsOrder ftsOrder=ftsOrderService.getOne(queryWrapper);
        /*********************************/
        FtsUserAddress ftsUserAddress=ftsUserAddressService.getById(ftsOrder.getShippingAddressId());
        ftsOrder.setShippingAddressData(ftsUserAddress);
        /*********************************/
        QueryWrapper ftsQuery=new QueryWrapper();
        ftsQuery.eq("order_code",orderCode);
        List<FtsOrderList> ftsOrderListList=ftsOrderListService.list(ftsQuery);
        ftsOrder.setFtsOrderListList(ftsOrderListList);
        /**************************************/
        ftsOrder.setPayUser(TokenUtil.getTokenUser());
        return Result.SUCCESS(ftsOrder);
    }

    @GetMapping("/listPage")
    @ResponseBody
    public Result listPage(Integer page, Integer pageSize, String where) {
        Page<FtsOrder> pageParams = new Page<FtsOrder>(page, pageSize);
        QueryWrapper<FtsOrder> queryWrapper = new QueryWrapper<FtsOrder>();
        if (StringUtils.isNotEmpty(where)) {
            if (where.contains("&")) {
                String[] whereDatas = where.split("&");
                for (String whereStr : whereDatas) {
                    String[] whereParam = whereStr.split("=");
                    if(!"state".equals(whereParam[0])&&!"0".equals(whereParam[1])){
                        queryWrapper.eq(whereParam[0], whereParam[1]);
                    }
                }
            } else {
                if (where.contains("=")) {
                    String[] whereParam = where.split("=");
                    if(!"state".equals(whereParam[0])&&!"0".equals(whereParam[1])){
                        queryWrapper.eq(whereParam[0], whereParam[1]);
                    }
                } else if (where.contains("=")) {
                    String[] whereParam = where.split("like");
                    if(!"state".equals(whereParam[0])&&!"0".equals(whereParam[1])){
                        queryWrapper.eq(whereParam[0], whereParam[1]);
                    }
                }

            }
        }
        queryWrapper.orderByDesc("create_time");
        IPage<FtsOrder> pageData = this.ftsOrderService.page(pageParams, queryWrapper);
        List<FtsOrder> ftsOrderList=pageData.getRecords();
        ftsOrderList.stream().forEach(item->{
            QueryWrapper orderListQuery=new QueryWrapper();
            Integer orderId=item.getId();
            orderListQuery.eq("order_id",orderId);
            item.setFtsOrderListList(this.ftsOrderListService.list(orderListQuery));
        });
        return Result.SUCCESS(ftsOrderList);
    }
/************************以下是退款*****************************************/
    /**
     * 目前支持订单全额退
     * @param orderCode
     * @return
     */
    @LoginAuth(flag = true)
    @RequestMapping("/refundOrder")
    public Result refundOrder(String orderCode){
        return  Result.SUCCESS(orderCode);
    }
}
